﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;

namespace RebEngine.GameComponents
{
    public class TickTimer
    {
        static List<TickTimer> Timers = new List<TickTimer>();

        private int iTicksRemaining;
        private int iInterval;

        private bool bContinousTimer;

        public delegate void Fire ();
        public event Fire TickTimerFinished;

        public void Start(int interval, bool continuous)
        {
            Timers.Remove(this);
            Timers.Add(this);
            this.iInterval = interval;
            this.iTicksRemaining = interval;
            bContinousTimer = continuous;
        }
          
        public void Stop()
        {
            Timers.Remove(this);
        }

        public static void Tick()
        {
            for (int i = Timers.Count - 1; i >= 0; i--)
            {
                Timers[i].iTicksRemaining --;
                if (Timers[i].iTicksRemaining <= 0)
                {
                    Timers[i].TickTimerFinished();
                    if (Timers[i].bContinousTimer == false)
                        Timers[i].Stop();
                    else
                        Timers[i].iTicksRemaining = Timers[i].iInterval;
                }
            }
        }

        public void ChangeInterval(int seconds)
        {
            iInterval = seconds;
        }

    }
}
